package com.czmh.etc.interpreter.entity.base;

/**
 * Created by Huangyk on 2019/6/4.
 */
public class CRC32 {
    private static long[] crc32_table = null;

    static {

    }

    private static long[] CRC_Init_CRC32_Table(){
        long ulPolynomial = 0x04c11db7;
        long[] table = new long[256];
        for(int i = 0; i <= 0xFF; i++){
            table[i] = CRC_Reflect(i, (byte)8) << 24;
            for(int j = 0; j < 8; j++){
                table[i] = (table[i] << 1) ^ ((table[i] & (1 << 31)) != 0 ? ulPolynomial : 0);
            }

            table[i] = CRC_Reflect(table[i], (byte)32);
        }

        return table;
    }

    /**
     * 按bit位倒置ref，用于CRC_Init_CRC32_Table
     * @param rf 待倒置数字
     * @param ch bit长度
     * @return 调转后的无符号长整数
     */
    private static int CRC_Reflect(long rf, byte ch){
        int value = 0;
        byte i;

        for(i = 1; i < (ch + 1); i++){
            if((rf & 1) != 0){
                value |= (int)1 << (ch - i);
            }

            rf >>= 1;
        }

        return value;
    }

    public static String CRC_ToStr(long crc){
        return String.format("%08x");
    }
}
